/**  
 * @Title: PortalController.java
 * @Package com.bw30.bwr.controller
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 国实  
 * @date Apr 6, 2010 3:34:19 PM
 * @version V1.0  
 */
package com.begamer.card.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.begamer.card.cache.Cache;
import com.begamer.card.common.Constant;
import com.begamer.card.common.dao.hibernate.CommDao;
import com.begamer.card.common.util.RandomId;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.BinReader;
import com.begamer.card.common.util.binRead.CardData;
import com.begamer.card.common.util.binRead.EquipData;
import com.begamer.card.common.util.binRead.ItemsData;
import com.begamer.card.common.util.binRead.PassiveSkillData;
import com.begamer.card.common.util.binRead.ServersData;
import com.begamer.card.common.util.binRead.SkillData;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.ManagerLogger;
import com.begamer.card.model.dao.AnnounceDao;
import com.begamer.card.model.pojo.Announce;
import com.begamer.card.model.pojo.Gift;
import com.begamer.card.model.pojo.Key;

/**
 * 
 * @ClassName: PortalController
 * @author 国实
 * @date Feb 23, 2011 11:12:28 AM
 * 
 */
public class UserController extends AbstractMultiActionController {
	
	private static final Logger logger = Logger.getLogger(UserController.class);
	private static final Logger errorlogger = ErrorLogger.logger;
	private static final Logger managerLogger = ManagerLogger.logger;
	
	@Autowired
	private AnnounceDao announceDao;
	@Autowired
	private CommDao commDao;

	public ModelAndView showAnnounce(HttpServletRequest request,
			HttpServletResponse response) {
		List<Announce> announces = announceDao.find();
		request.setAttribute("announce", announces);
		return new ModelAndView("/gonggao/gonggao.vm");
	}

	// 修改公告
	public ModelAndView updateAnnounce(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Cache.announce = request.getParameter("announce");
			List<Announce> announces = announceDao.find();
			for (Announce announce : announces) {
				announce.setAnnounce(request.getParameter("announce"));
				announceDao.update(announce);
			}
			managerLogger.info(getManager(request).getName() + "|修改了游戏公告!"
					+ "|登录IP：" + request.getRemoteAddr());
			List<Announce> annList = announceDao.find();
			request.setAttribute("announce", annList);
		} catch (Exception e) {
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
		}
		return new ModelAndView("/gonggao/gonggao.vm");
	}

	// 礼包列表
	public ModelAndView giftList(HttpServletRequest request,
			HttpServletResponse response) {
		int pageId = StringUtil.getInt(request.getParameter("pageId"));
		if (pageId < 0) {
			return null;
		}
		if (pageId == 0) {
			pageId = 1;
		}
		// 分页查询
		List<Gift> list = commDao.getGifts(pageId - 1, Constant.PageSize);
		int giftCount = commDao.getGiftCount();
		int pageTotal = 0;
		if (giftCount % Constant.PageSize == 0) {
			pageTotal = giftCount / Constant.PageSize;
		} else {
			pageTotal = giftCount / Constant.PageSize + 1;
		}
		request.setAttribute("pageId", pageId);
		request.setAttribute("pageTotal", pageTotal);
		request.setAttribute("list", list);
		return new ModelAndView("/user/giftList.vm");
	}

	// 条件查询
	public ModelAndView inquireCenter(HttpServletRequest request,
			HttpServletResponse response) {
		int type = Integer.parseInt(request.getParameter("type"));
		String keyword = request.getParameter("keyword");
		if (type == 1) {
			getGiftByGName(request, keyword);
		}
		request.setAttribute("type", type);
		request.setAttribute("keywork", keyword);
		return new ModelAndView("user/onegift.vm");
	}

	public void getGiftByGName(HttpServletRequest request, String name) {
		int pageId = StringUtil.getInt(request.getParameter("pageId"));
		if (pageId == 0) {
			pageId = 1;
		}
		// 分页查询
		List<Gift> list = commDao.getGiftByGName(pageId - 1, Constant.PageSize,
				name);
		int giftCount = commDao.getGiftByGName(name).size();
		int pageTotal = 0;
		if (giftCount % Constant.PageSize == 0) {
			pageTotal = giftCount / Constant.PageSize;
		} else {
			pageTotal = giftCount / Constant.PageSize + 1;
		}
		request.setAttribute("pageId", pageId);
		request.setAttribute("pageTotal", pageTotal);
		request.setAttribute("list", list);
	}

	// 创建礼包页
	public ModelAndView preCreateGift(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("preCreateGift.jsp");
	}

	// 创建礼包、激活码
	public ModelAndView createGift(HttpServletRequest request,
			HttpServletResponse response) {
		// 激活码个数
		int num = StringUtil.getInt(request.getParameter("num"));
		String name = request.getParameter("name");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");

		int gold = StringUtil.getInt(request.getParameter("gold"));
		int crystal = StringUtil.getInt(request.getParameter("crystal"));
		int runeNum = StringUtil.getInt(request.getParameter("runeNum"));
		int power = StringUtil.getInt(request.getParameter("power"));

		String card = request.getParameter("cardId");
		String skill = request.getParameter("skillId");
		String pSkill = request.getParameter("pSkillId");
		String equip = request.getParameter("equipId");
		String item = request.getParameter("itemId");

		// 检验数据有效性
		if (startDate == null || "".equals(startDate) || endDate == null
				|| "".equals(endDate) || startDate.compareTo(endDate) > 0) {
			request.setAttribute("result", "日期无效");
			return new ModelAndView("preCreateGift.jsp");
		}
		if (num < 0 || gold < 0 || crystal < 0 || runeNum < 0 || power < 0) {
			request.setAttribute("result", "数据出错:不能为负数");
			return new ModelAndView("preCreateGift.jsp");
		}
		boolean is = false;
		String result = null;
		String[] cardId = card.split(",");
		for (int i = 0; i < cardId.length; i++) {
			String[] cid = cardId[i].split("-");
			if (card != null && card.trim().length() > 0 && cid.length == 2) {
				if (StringUtil.isNumeric(cid[0])
						|| StringUtil.isNumeric(cid[1])) {
					is = true;
					result = cid[0] + "请输入数字!";
					break;
				}
			}
			if (card != null && card.trim().length() > 0 && cid.length != 2) {
				is = true;
				result = cid[0] + "的个数输入错误！";
				break;
			}
			if (card != null && card.trim().length() > 0
					&& CardData.getData(StringUtil.getInt(cid[0])) == null) {
				is = true;
				result = cid[0];
				break;
			}
		}
		if (is) {
			request.setAttribute("result", "无英雄卡数据:" + result);
			return new ModelAndView("preCreateGift.jsp");
		}
		String[] skillId = skill.split(",");
		for (int i = 0; i < skillId.length; i++) {
			String[] sid = skillId[i].split("-");
			if (skill != null && skill.trim().length() > 0 && sid.length == 2) {
				if (StringUtil.isNumeric(sid[0])
						|| StringUtil.isNumeric(sid[1])) {
					is = true;
					result = sid[0] + "请输入数字!";
					break;
				}
			}
			if (skill != null && skill.trim().length() > 0 && sid.length != 2) {
				is = true;
				result = sid[0] + "的个数输入错误！";
				break;
			}
			if (skill != null && skill.trim().length() > 0
					&& SkillData.getData(StringUtil.getInt(sid[0])) == null) {
				is = true;
				result = sid[0];
				break;
			}
		}
		if (is) {
			request.setAttribute("result", "无主动技能数据:" + result);
			return new ModelAndView("preCreateGift.jsp");
		}
		String[] pSkillId = pSkill.split(",");
		for (int i = 0; i < pSkillId.length; i++) {
			String[] psid = pSkillId[i].split("-");
			if (pSkill != null && pSkill.trim().length() > 0
					&& psid.length == 2) {
				if (StringUtil.isNumeric(psid[0])
						|| StringUtil.isNumeric(psid[1])) {
					is = true;
					result = psid[0] + "请输入数字!";
					break;
				}
			}
			if (pSkill != null && pSkill.trim().length() > 0
					&& psid.length != 2) {
				is = true;
				result = psid[0] + "的个数输入错误！";
				break;
			}
			if (pSkill != null
					&& pSkill.trim().length() > 0
					&& PassiveSkillData.getData(StringUtil.getInt(psid[0])) == null) {
				is = true;
				result = psid[0];
				break;
			}
		}
		if (is) {
			request.setAttribute("result", "无被动技能数据:" + result);
			return new ModelAndView("preCreateGift.jsp");
		}
		String[] equipId = equip.split(",");
		for (int i = 0; i < equipId.length; i++) {
			String[] eid = equipId[i].split("-");
			if (equip != null && equip.trim().length() > 0 && eid.length == 2) {
				if (StringUtil.isNumeric(eid[0])
						|| StringUtil.isNumeric(eid[1])) {
					is = true;
					result = equipId[0] + "请输入数字!";
					break;
				}
			}
			if (equip != null && equip.trim().length() > 0 && eid.length != 2) {
				is = true;
				result = eid[0] + "的个数输入错误！";
				break;
			}
			if (equip != null && equip.trim().length() > 0
					&& EquipData.getData(StringUtil.getInt(eid[0])) == null) {
				is = true;
				result = eid[0];
				break;
			}
		}
		if (is) {
			request.setAttribute("result", "无装备数据:" + result);
			return new ModelAndView("preCreateGift.jsp");
		}
		String[] itemId = item.split(",");
		for (int i = 0; i < itemId.length; i++) {
			String[] iid = itemId[i].split("-");
			if (item != null && item.trim().length() > 0 && iid.length == 2) {
				if (StringUtil.isNumeric(iid[0])
						|| StringUtil.isNumeric(iid[1])) {
					is = true;
					result = iid[0] + "请输入数字!";
					break;
				}
			}
			if (item != null && item.trim().length() > 0 && iid.length != 2) {
				is = true;
				result = equipId[0] + "的个数输入错误！";
				break;
			}
			if (item != null
					&& item.trim().length() > 0
					&& ItemsData.getItemsData(StringUtil.getInt(iid[0])) == null) {
				is = true;
				result = iid[0];
				break;
			}
		}
		if (is) {
			request.setAttribute("result", "无材料数据:" + result);
			return new ModelAndView("preCreateGift.jsp");
		}
		Gift gift = new Gift(name, gold, crystal, runeNum, power, card, skill,
				pSkill, equip, item, startDate, endDate, startDate, num);
		int giftId = commDao.saveGift(gift);
		if (giftId > 0) {
			int maxId = commDao.getMaxKeyId();
			// 生成激活码
			RandomId r = new RandomId();

			List<Key> keys = new ArrayList<Key>();
			for (int i = (maxId + 1); i < (maxId + 1 + num); i++) {
				Key key = new Key();
				key.setCode(r.randomId(i));
				key.setStatus(0);
				key.setGiftId(giftId);
				keys.add(key);
			}
			commDao.saveKeys(keys);
		}
		managerLogger.info(getManager(request).getName() + "|创建礼包、激活码"
				+ "|礼包名称:" + name + "|激活码个数：" + num + "|登录IP："
				+ request.getRemoteAddr());
		Cache.getInstance().loadGift();// 重载激活码
		return giftList(request, response);
	}

	// 追加激活码页面
	public ModelAndView preAddKey(HttpServletRequest request,
			HttpServletResponse response) {
		int id = StringUtil.getInt(request.getParameter("id"));
		if (id <= 0) {
			return null;
		}
		Gift gift = commDao.getGift(id);
		request.setAttribute("gift", gift);
		return new ModelAndView("/user/preAddKey.vm");
	}

	// 追加激活码
	public ModelAndView addKey(HttpServletRequest request,
			HttpServletResponse response) {
		int giftId = StringUtil.getInt(request.getParameter("id"));
		int num = StringUtil.getInt(request.getParameter("num"));
		if (giftId > 0 && num > 0) {
			int maxId = commDao.getMaxKeyId();
			// 生成激活码
			RandomId r = new RandomId();
			List<Key> keys = new ArrayList<Key>();
			for (int i = (maxId + 1); i < (maxId + 1 + num); i++) {
				Key key = new Key();
				key.setCode(r.randomId(i));
				key.setStatus(0);
				key.setGiftId(giftId);
				keys.add(key);
			}
			commDao.saveKeys(keys);
			commDao.updateGift(giftId, num);
		}
		managerLogger.info(getManager(request).getName() + "|追加激活码" + "|礼包编号："
				+ giftId + "|追加个数：" + num + "|登录IP：" + request.getRemoteAddr());
		Cache.getInstance().loadGift();// 重载激活码
		request.setAttribute("result", "操作成功!");
		return giftList(request, response);
	}

	// 导出激活码
	public ModelAndView exportKeys(HttpServletRequest request,
			HttpServletResponse response) {
		int giftId = StringUtil.getInt(request.getParameter("id"));
		if (giftId <= 0) {
			return null;
		}
		List<Key> list = commDao.getKeys(giftId);
		byte[] bs = getTxtBytes(list);
		try {
			downLoad(request, response, bs);
			managerLogger.info(getManager(request).getName() + "|导出礼包激活码"
					+ "|礼包ID:" + giftId + "|登录IP：" + request.getRemoteAddr());
		} catch (Exception e) {
			logger.error(e);
		}
		return null;
	}

	private void downLoad(HttpServletRequest request,
			HttpServletResponse response, byte[] bs) throws Exception {
		// 设置文件的类型
		logger.debug("开始下载key文件");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String("key.txt".getBytes("utf-8"), "ISO-8859-1"));
		response.addHeader("Content-Length", "" + bs.length);
		OutputStream toClient = new BufferedOutputStream(response
				.getOutputStream());
		response.setContentType("txt/html");
		toClient.write(bs);
		toClient.flush();
		toClient.close();
	}

	private static byte[] getTxtBytes(List<Key> list) {
		StringBuffer sb = new StringBuffer();
		try {
			for (Key key : list) {
				sb.append(key.getCode() + "\t\n");
			}
		} catch (Exception e) {
			logger.debug(e.toString(), e);
		}
		return sb.toString().getBytes();
	}

	// 删除礼包
	public ModelAndView deleteGift(HttpServletRequest request,
			HttpServletResponse response) {
		int id = StringUtil.getInt(request.getParameter("id"));
		Cache.getInstance().deleteGift(id);
		commDao.deleteGift(id);
		managerLogger.info(getManager(request).getName() + "|删除礼包：" + id
				+ "|登录IP：" + request.getRemoteAddr());
		request.setAttribute("result", "操作成功!");
		return giftList(request, response);
	}

	public ModelAndView server(HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("servers", ServersData.getDatas());
		return new ModelAndView("centre/server.vm");
	}

	public ModelAndView upServerType(HttpServletRequest request,
			HttpServletResponse response) {
		int serverId = Integer.parseInt(request.getParameter("serverId"));
		int type = Integer.parseInt(request.getParameter("type"));
		for (ServersData serversData : ServersData.getDatas()) {
			if (serversData.id == serverId) {
				serversData.setType(type);
			}
		}
		managerLogger.info(getManager(request).getName() + "|修改服务器Type"
				+ "|服务器ID：" + serverId + "|type:" + type + "|登录IP："
				+ request.getRemoteAddr());
		return server(request, response);
	}

	public ModelAndView reloadBins(HttpServletRequest request,
			HttpServletResponse response) {
		String reloadKey = request.getParameter("reloadKey");
		if ("9d33o2gm&#LJ@KNNasd./,2".equals(reloadKey)) {
			new BinReader().readAllData();
			request.setAttribute("msg", "重载完毕");
			managerLogger.info(getManager(request).getName() + "|重载bin文件|登录IP："
					+ request.getRemoteAddr());
		} else {
			request.setAttribute("msg", "请输入正确的密钥");
		}
		return new ModelAndView("reloadBin.jsp");
	}
}
